package com.baoyouqun.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.RoleCreateCmd;
import com.baoyouqun.domain.Query.RoleQuery;
import com.baoyouqun.domain.UpdateCmd.RoleUpdateCmd;
import com.baoyouqun.domain.VO.RoleVO;
import com.baoyouqun.entity.Permission;
import com.baoyouqun.entity.Role;
import com.baoyouqun.entity.RolePermission;
import com.baoyouqun.mapper.PermissionMapper;
import com.baoyouqun.mapper.RoleMapper;
import com.baoyouqun.service.RolePermissionService;
import com.baoyouqun.service.RoleService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    @Lazy
    private RolePermissionService rolePermissionService;
    @Resource
    private PermissionMapper permissionMapper;

    /**
     * 校验角色编码是否唯一
     */
    @Override
    public boolean checkRoleCodeUnique(String roleCode) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleCode, roleCode);
        return count(queryWrapper) == 0;
    }


    @Override
    public SingleResponse<RoleVO> create(RoleCreateCmd cmd) {
        // 1. 校验角色编码唯一性
        if (!checkRoleCodeUnique(cmd.getRoleCode())) {
            return SingleResponse.buildFailure("100401", "角色编码已存在，请更换编码");
        }

        // 2. 创建角色
        Role role = ConvertUtils.copyBean(cmd, Role.class);
        role.setId("R" + System.currentTimeMillis() % 1000000); // 简化ID生成，可替换为雪花ID
        boolean roleSave = save(role);
        if (!roleSave) {
            return SingleResponse.buildFailure("100402", "角色创建失败");
        }

        // 3. 批量绑定角色与权限（构建RolePermission列表）
        List<RolePermission> rolePermissionList = cmd.getPermissionIds().stream()
                .map(permId -> {
                    RolePermission rp = new RolePermission();
                    rp.setId("RP" + System.currentTimeMillis() % 1000000 + permId.hashCode() % 100); // 简化ID
                    rp.setRoleId(role.getId());
                    rp.setPermId(permId);
                    return rp;
                })
                .collect(Collectors.toList());

        boolean permSave = rolePermissionService.saveBatch(rolePermissionList);
        if (!permSave) {
            throw new RuntimeException("权限绑定失败，触发事务回滚"); // 回滚角色创建
        }

        // 4. 转换为VO返回
        RoleVO roleVO = ConvertUtils.copyBean(role, RoleVO.class);
        return SingleResponse.of(roleVO);
    }

    @Override
    public Response update(RoleUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        Role oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, Role.class);
        Boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public RoleVO selectById(String id) {
        Role entity = baseMapper.selectById(id);
        RoleVO vo =
                ConvertUtils.copyBean(entity, RoleVO.class);
        return vo;
    }

    @Override
    public IPage<RoleVO> pageVo(RoleQuery query) {
        IPage<Role> page = new Page<Role>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<Role>());
        Page<RoleVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        page.getRecords().forEach(entity -> {
            RoleVO vo =
                    ConvertUtils.copyBean(entity, RoleVO.class);
            voPage.getRecords().add(vo);
        });
        return voPage;
    }

    @Override
    public List<String> getPermissionsByRoleIds(List<String> roleIds) {
        if (CollUtil.isEmpty(roleIds)) {
            return new ArrayList<>();
        }
        // 查询角色关联的权限ID
        List<String> permissionIds = rolePermissionService.selectPermissionIdsByRoleIds(roleIds);
        // 查询权限标识（假设权限表有permission字段）
        return permissionMapper.selectByIds(permissionIds).stream()
                .map(Permission::getId)
                .collect(Collectors.toList());
    }

    @Override
    public SingleResponse<List<RoleVO>> getRoleList() {
        List<Role> roleList = list();
        return SingleResponse.of(ConvertUtils.copyBeanList(roleList, RoleVO.class));
    }
}